package com.im.oauth2.service;

import com.im.web.core.QueryUtils;
import com.im.web.core.model.UserInfo;
import com.im.web.core.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static com.im.common.Constants.IS_EXIST;
import static com.im.common.Constants.USER_AUTHORITY;
import static com.im.web.core.model.QUserInfo.userInfo;

/**
 * @author gongym
 * @date 2018年10月30日 上午12:03:05
 */
@Component
public class UserServiceImpl implements UserDetailsService {

  private UserInfoRepository userInfoRepository;

  @Autowired
  public UserServiceImpl(UserInfoRepository userInfoRepository) {
    this.userInfoRepository = userInfoRepository;
  }

  @SuppressWarnings("Duplicates")
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    QueryUtils queryUtils = new QueryUtils();
    queryUtils
        .putExpression(userInfo.delFlag.eq(IS_EXIST))
        .putExpression(userInfo.account.eq(username));
    Optional<UserInfo> userInfoOptional = userInfoRepository.findOne(queryUtils.buildQuery());
    UserInfo userInfo = userInfoOptional.orElse(null);
    if (null != userInfo) {
      // 获取用户密码，如果密码不匹配会登录失败
      return new User(
          username,
          userInfo.getPassword(),
          AuthorityUtils.commaSeparatedStringToAuthorityList(USER_AUTHORITY));
    } else {
      return null;
    }
  }
}
